#ifndef MODEM_H_
#define MODEM_H_

#include <assert.h>

#include <ctl.h>
#include <ctl_api.h>
#include <targets/lpc2378.h>
#include <targets/liblpc2000.h>
#include <cross_studio_io.h>

#include "timer.h"
#include "../utils/buffer.h"

#define IIR1 1
#define IIR2 2
#define IIR3 3

#define LSR_OE U1LSR_OE_MASK
#define LSR_PE U1LSR_PE_MASK
#define LSR_FE U1LSR_FE_MASK
#define LSR_RXFE U1LSR_RXFE_MASK
#define LSR_BI U1LSR_BI_MASK
#define LSR_RDR U1LSR_RDR_MASK

#define MODEM_BUFFER_SIZE 2048 + 1

#define MODEM_ENABLE_TXD_PIN() { PINSEL4 = (PINSEL4 & ~0x00000003) | 0x00000002; }
#define MODEM_ENABLE_RXD_PIN() { PINSEL4 = (PINSEL4 & ~0x0000000C) | 0x00000008; }
#define MODEM_ENABLE_CTS_PIN() { PINSEL4 = (PINSEL4 & ~0x00000030) | 0x00000020; }
#define MODEM_ENABLE_RTS_PIN() { PINSEL4 = (PINSEL4 & ~0x0000C000) | 0x00008000; }
#define MODEM_SET_RTS()        {FIO2DIR |= 0x00000080; FIO2SET =  0x00000080;}
#define MODEM_CLR_RTS()        {FIO2DIR |= 0x00000080; FIO2CLR =  0x00000080;}
//#define MODEM_SET_DTR()        {FIO2DIR |= 0x00000020; FIO2CLR =  0x00000020;}
//#define MODEM_CLR_DTR()        {FIO2DIR |= 0x00000020; FIO2CLR =  0x00000020;}

// DTR на GSM-модем
#define DTR1_PIN            5
#define DTR1_SETPORT        FIO2SET
#define DTR1_CLRPORT        FIO2CLR
#define DTR1_DIRPORT        FIO2DIR
#define DTR1_SET()          DTR1_SETPORT=(1<<DTR1_PIN)
#define DTR1_CLR()          DTR1_CLRPORT=(1<<DTR1_PIN)

#define MODEM_CLR_DTR()  {DTR1_DIRPORT|= (1<<DTR1_PIN); DTR1_CLRPORT=(1<<DTR1_PIN); }
#define MODEM_SET_DTR()  {DTR1_DIRPORT|= (1<<DTR1_PIN); DTR1_SETPORT=(1<<DTR1_PIN); }


/* Initialize modem with any baud: 0(autobaud), 300, 1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200 */
void modem_init(unsigned int baud);

/* Turn modem on */
void modem_on();

/* Turn modem off */
void modem_off();
  
/* Turn on internal loopback mode */
void modem_loopbackon();
  
/* Turn off internal loopback mode */
void modem_loopbackoff();

/* Get number of available bytes in buffer */
int  modem_available();

/* Read data from modem buffer. Returns number of bytes read */
int  modem_read(char* dest, int length);

/* Send a single character using polling */
void modem_putc(char c);

/* Send string using polling */
void modem_puts(char *str);

/* Send buffer using polling */
void modem_putn(char *str, int len);

/* Flush modem input buffer */
void modem_flush();


#endif